import React, { useEffect } from 'react'
import { Terminal } from "xterm";
import { FitAddon } from "xterm-addon-fit";
import 'xterm/css/xterm.css'
import styles from './index.less'

interface PodTerminalProps {
  url: string
  pod: string
  namespace: string
  command: string
}

const PodTerminal: React.FC<PodTerminalProps> = ({
  url,
  pod,
  namespace,
  command
}) => {

  useEffect(() => {
    const wsUrl = `${url}?pod=${pod}&namespace=${namespace}&command=${command}`
    console.log(wsUrl);

    const ws = new WebSocket(wsUrl);
    let terminal = new Terminal({ cursorBlink: true });

    ws.onopen = () => {
      const msg = { operation: "stdin", data: "export TERM=xterm && clear \r" }
      ws.send(JSON.stringify(msg))
    }

    ws.onmessage = (event) => {
      const msg = JSON.parse(event.data)
      if (msg.operation === "stdout") {
        terminal.write(msg.data);
      } else {
        console.log("invalid msg operation: " + msg)
      }
    }
    ws.onclose = () => {
      terminal.writeln("Exit");
    }
    ws.onerror = () => {
      terminal.writeln("");
      terminal.writeln("Sorry, connection has some error.");
    }

    let fitAddon = new FitAddon();
    terminal.loadAddon(fitAddon);

    // @ts-ignore
    terminal.open(document.getElementById("terminal"));
    terminal.focus()
    terminal.onResize(({ cols, rows }) => {
      const msg = { operation: "resize", cols: cols, rows: rows }
      ws.send(JSON.stringify(msg));
    });

    terminal.onData((data) => {
      const msg = { operation: "stdin", data: data }
      ws.send(JSON.stringify(msg));
    });

  }, [url, pod, namespace, command])

  return (
    <div id="terminal" className={styles.box} style={{ height: '100vh' }}></div>
  )
}

export default PodTerminal
export {
  PodTerminal
}
